{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 1. pb文件的保存方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Froze 2 variables.\n",
      "Converted 2 variables to const ops.\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.python.framework import graph_util\n",
    "\n",
    "v1 = tf.Variable(tf.constant(1.0, shape=[1]), name = \"v1\")\n",
    "v2 = tf.Variable(tf.constant(2.0, shape=[1]), name = \"v2\")\n",
    "result = v1 + v2\n",
    "\n",
    "init_op = tf.global_variables_initializer()\n",
    "with tf.Session() as sess:\n",
    "    sess.run(init_op)\n",
    "    graph_def = tf.get_default_graph().as_graph_def()\n",
    "    output_graph_def = graph_util.convert_variables_to_constants(sess, graph_def, ['add'])\n",
    "    with tf.gfile.GFile(\"Saved_model/combined_model.pb\", \"wb\") as f:\n",
    "           f.write(output_graph_def.SerializeToString())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 2. 加载pb文件。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[array([ 3.], dtype=float32)]\n"
     ]
    }
   ],
   "source": [
    "from tensorflow.python.platform import gfile\n",
    "with tf.Session() as sess:\n",
    "    model_filename = \"Saved_model/combined_model.pb\"\n",
    "   \n",
    "    with gfile.FastGFile(model_filename, 'rb') as f:\n",
    "        graph_def = tf.GraphDef()\n",
    "        graph_def.ParseFromString(f.read())\n",
    "\n",
    "    result = tf.import_graph_def(graph_def, return_elements=[\"add:0\"])\n",
    "    print(sess.run(result))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
